import { CONFIG } from '@/constants';
import { getBase64 } from '@/utils';
import { PlusOutlined } from '@ant-design/icons';
import { GetProp, Modal, Upload, UploadFile, UploadProps, message } from 'antd';
import { useEffect, useState } from 'react';

const FormImages: React.FC<IBuildForm.Params> = (props) => {
    const beforeUpload = (file: FileType) => {
        const isJpgOrPng =
            file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M  || Upload.LIST_IGNORE;
    };
    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
        </button>
    );

    type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');
    const handleCancel = () => setPreviewOpen(false);
    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as FileType);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
        setPreviewTitle(
            file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1),
        );
    };
    useEffect(() => {}, []);
    return (
        <>
            <Upload
                {...props}
                listType="picture-card"
                beforeUpload={beforeUpload}
                action={CONFIG.HTTP_REQUEST_URL + '/common/upload'}
                onPreview={handlePreview}
            >
                {uploadButton}
            </Upload>
            <Modal
                open={previewOpen}
                title={previewTitle}
                footer={null}
                onCancel={handleCancel}
            >
                <img
                    alt="example"
                    style={{ width: '100%' }}
                    src={previewImage}
                />
            </Modal>
        </>
    );
};
export default FormImages;
